<?php

declare(strict_types=1);


namespace App\Resource\Service;


use App\Activity\Model\ActivityGoodsModel;
use App\Activity\Model\ActivityModel;
use App\Common\Constants\ErrorCode;
use App\Common\Service\BaseService;
use App\Common\Job\LogJob;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use App\Resource\Repository\RepositoryFactory;
use App\Order\Model\OrderGoodsModel;
use App\Resource\Model\CartModel;
use App\Resource\Model\GoodsModel;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class CartService extends BaseService
{
    /**
     * 商品是否有效 0有效商品 1无效商品
     */
    const GOODS_STATUS_0 = 0;
    const GOODS_STATUS_1 = 1;
    /**
     *  0及时达 1次日达
     */
    const CART_SOURCE_0 = 0;
    const CART_SOURCE_1 = 1;
    /**
     * @Inject()
     * @var GoodsService
     */
    private $goodsService;
    protected $cartLog;
    protected $goodsRepository;
    public function __construct(DriverFactory $driverFactory,RepositoryFactory $repoFactory)
    {
        parent::__construct();
        $this->cartLog = $driverFactory->get('log');
        $this->goodsRepository = $repoFactory->getRepository('goods');
    }

    /**
     * 根据会员id及商品id 更新/新增 购物车信息
     * @param int $mid
     * @param int $goodsId
     * @param array $updateOrAddData
     * @param int $group_id
     * @param int $shop_id
     * @param int $activityGoodsId
     * @return bool | array
     * @throws \Exception
     */
    public function setInfoGoodsId(int $mid, int $goodsId, array $updateOrAddData, int $group_id, int $shop_id, int $activityGoodsId)
    {
        $where = [
            'id' => $goodsId,
            'status' => 1,
            'is_deleted' => 0,
            'is_today' => '1'
        ];
        //及时达更新购物车(商品选中状态判断商品失效状态)
        if (!self::isEffectiveByGoodsId($where, $shop_id)) {
            return ['code' => ErrorCode::GOODS_INVALID];
        }
        //读pos库存   scant_id 标品非标品  ratio 商品转换系数  surplusQuantity 剩余数量
        if ($updateOrAddData['is_selected'] != 0 && $updateOrAddData['goods_num'] > 0) {
            $goodsStock = $this->goodsService->getGoodsInfoDataArr($shop_id,$goodsId)[0];
            if ($goodsStock['scant_id'] == GoodsService::GOODS_SCANT_1) {
                $stock = $goodsStock['ratio'] ? bcdiv((string)$goodsStock['surplusQuantity'], (string)$goodsStock['ratio']) : (string)$goodsStock['surplusQuantity'];
            } else {
                $stock = bcdiv((string)$goodsStock['surplusQuantity'], '1000');
            }
            if (!self::checkStock((int)$stock, (int)$updateOrAddData['goods_num'],(int) $shop_id, (int)$goodsId, $goodsStock['scant_id'], $goodsStock['ratio'])) {
                return ['code' => ErrorCode::GOODS_SELL_OUT];
            }
        }
        $datetime = date('Y-m-d H:i:s');
        $cartObj = CartModel::query()->where(['mid' => $mid, 'goods_id' => $goodsId,'shop_id' => $shop_id,'group_id' => $group_id,'activity_goods_id'=>$activityGoodsId,'source'=>1])->first();
        // 检测限购 根据活动商品id
        if ($activityGoodsId > 0) {
            $returnInfo = self::checkGoodsLimits((int) $activityGoodsId,(int) $updateOrAddData['goods_num'], $mid);
            if ($returnInfo['code']) {
                return ['code' => ErrorCode::GOODS_NUM_OVER];
            }
        }
        if ($cartObj) {
            if (isset($updateOrAddData['goods_num'])) {//删除商品
                $goodsNum = $updateOrAddData['goods_num'];
                if ($updateOrAddData['goods_num'] == 0 || $goodsNum <= 0) {
                    if ($cartObj->delete()) {
                        return ['code' => ErrorCode::SUCCESS];
                    } else {
                        return ['code' => ErrorCode::CART_CLEAR_FAIL];
                    }
                }
                $updateOrAddData['goods_num'] = $goodsNum;
            }

            $updateOrAddData['update_at'] = $datetime;
            CartModel::query()->where(['id' => $cartObj['id']])->update($updateOrAddData);
            return ['code' => ErrorCode::SUCCESS];
        } else {
            //新增商品
            $updateOrAddData['mid'] = $mid;
            $updateOrAddData['goods_id'] = $goodsId;
            $updateOrAddData['create_at'] = $datetime;
            $updateOrAddData['shop_id'] = $shop_id;
            $updateOrAddData['source'] = 1;
            $updateOrAddData['group_id'] = $group_id;
            $updateOrAddData['activity_goods_id'] = $activityGoodsId;
            if(self::cartInsert($updateOrAddData)){
                return ['code' => ErrorCode::SUCCESS];
            }
        }
    }

    /**
     * 批量处理购物车
     * @param int $mid
     * @param int $shop_id
     * @param array $goods_list
     * @param array|string[] $field
     * @return array|mixed
     */
    public function batchCart(int $mid, int $shop_id, array $goods_list, array $field = ['*'])
    {
        $goodsIdsArr = array_column($goods_list, 'goods_id');
        $group_id = array_column($goods_list,'group_id');
        $activityId = array_column($goods_list,'activity_goods_id');
        $cartListArr = CartModel::query()->select($field)->where(['mid' => $mid,'shop_id'=>$shop_id,'source'=>1,'group_id'=>$group_id[0],'activity_goods_id'=>$activityId[0]])->whereIn('goods_id', $goodsIdsArr)->get()->toArray();
        $cartListArrByMid = $updateOrAddData = [];
        if ($cartListArr) {
            $cartListArrByMid = array_column($cartListArr, null, 'goods_id');
        }
        $_goodsStoreArr = $this->goodsService->getGoodsInfoData($shop_id, $goodsIdsArr);
        $goodsStoreArr = array_column($_goodsStoreArr, null, 'goods_id');
        $datetime = date('Y-m-d H:i:s');
        Db::beginTransaction();
        try {
            foreach ($goods_list as $arr) {
                if (!isset($goodsStoreArr[$arr['goods_id']])) {
                    continue;
                }
                //读POS
                if (isset($cartListArrByMid[$arr['goods_id']])) {
                    $num = $cartListArrByMid[$arr['goods_id']]['goods_num'] + $arr['goods_num'];
                    if ($goodsStoreArr[$arr['goods_id']]['scant_id'] == $this->goodsService::GOODS_SCANT_1) {
                        $stock = $goodsStoreArr[$arr['goods_id']]['ratio'] ? bcdiv((string)$goodsStoreArr[$arr['goods_id']]['surplusQuantity'], (string)$goodsStoreArr[$arr['goods_id']]['ratio']) : (string)$goodsStoreArr[$arr['goods_id']]['surplusQuantity'];
                    } else {
                        $stock = bcdiv((string)$goodsStoreArr[$arr['goods_id']]['surplusQuantity'], '1000');
                    }
                    if ($goodsStoreArr[$arr['goods_id']]['read_pos_stock'] == $this->goodsService::GOODS_READ_POS_STOCK_1){
                        if ($stock < $num) {
                            if (!$this->checkStock((int)$stock, $num, $shop_id, $arr['goods_id'], $goodsStoreArr[$arr['goods_id']]['scant_id'], $goodsStoreArr[$arr['goods_id']]['ratio'])) {
                                Db::rollBack();
                                return ['code' => ErrorCode::GOODS_SELL_OUT];
                            }
                        }
                    }
                    // 检测限购
                    if (isset($arr['activity_goods_id']) && $arr['activity_goods_id'] > 0) {
                        $returnInfo = self::checkGoodsLimits($arr['activity_goods_id'], $num, $mid);
                        if ($returnInfo['code']) {
                            Db::rollBack();
                            return ['code' =>ErrorCode::GOODS_NUM_OVER];
                        }
                    }
                    $tempArr = [
                        'goods_num' => $cartListArrByMid[$arr['goods_id']]['goods_num'] + $arr['goods_num'],
                    ];
                    if ($arr['is_selected']) {
                        $tempArr['is_selected'] = $arr['is_selected'];
                    }
                    $tempArr['update_at'] = $datetime;
                    CartModel::query()->where(['mid' => $mid, 'goods_id' => $arr['goods_id'],'shop_id'=>$shop_id,'source'=>1,'group_id'=>$group_id[0],'activity_goods_id'=>$activityId[0]])->update($tempArr);
                    $this->saveCartLog('success',$tempArr,self::CART_SOURCE_0,'成功');
                } else {
                    $num = $arr['goods_num'];
                    if ($goodsStoreArr[$arr['goods_id']]['scant_id'] == $this->goodsService::GOODS_SCANT_1) {
                        $stock = $goodsStoreArr[$arr['goods_id']]['ratio'] ? bcdiv((string)$goodsStoreArr[$arr['goods_id']]['surplusQuantity'], (string)$goodsStoreArr[$arr['goods_id']]['ratio']) : (string)$goodsStoreArr[$arr['goods_id']]['surplusQuantity'];
                    } else {
                        $stock = bcdiv((string)$goodsStoreArr[$arr['goods_id']]['surplusQuantity'], '1000');
                    }
                    if (!$this->checkStock((int)$stock, $num, $shop_id, $arr['goods_id'], $goodsStoreArr[$arr['goods_id']]['scant_id'], $goodsStoreArr[$arr['goods_id']]['ratio'])) {
                        Db::rollBack();
                        return ['code' => ErrorCode::GOODS_SELL_OUT];
                    }
                    if (isset($arr['activity_goods_id']) && $arr['activity_goods_id'] > 0) {
                        $returnInfo = self::checkGoodsLimits($arr['activity_goods_id'], $num, $mid);
                        if ($returnInfo['code']) {
                            Db::rollBack();
                            return ['code' =>ErrorCode::GOODS_NUM_OVER];
                        }
                    }
                    $updateOrAddData[] = [
                        'mid' => $mid,
                        'shop_id' => $shop_id,
                        'goods_id' => $arr['goods_id'],
                        'goods_num' => $arr['goods_num'],
                        'activity_goods_id' => $arr['activity_goods_id'] ?? 0,
                        'group_id' => $arr['group_id'] ?? 0,
                        'is_selected' => $arr['is_selected'],
                        'source' => 1,
                        'create_at' => $datetime
                    ];
                }
            }
            if ($updateOrAddData){
                self::cartInsert($updateOrAddData);
                $this->saveCartLog('success',$updateOrAddData,self::CART_SOURCE_0,'成功');
            }
            Db::commit();
            return ['code' => ErrorCode::SUCCESS];
        } catch (\Throwable $ex) {
            Db::rollBack();
            $this->saveCartLog('error',[$mid,$shop_id,$goods_list],self::CART_SOURCE_0,$ex->getMessage());
            return ['code' => ErrorCode::NOT_IN_FORCE];
        }
    }

    /**
     * 校验商品是否有效
     * @param array $where
     * @param int $shop_id
     * @return bool
     */
    public static function isEffectiveByGoodsId(array $where, int $shop_id)
    {
        $goodsObj = GoodsModel::query()->where($where)->whereRaw('!FIND_IN_SET(?,shop_ids)', [$shop_id])->value('id');
        if ($goodsObj) {
            return true;
        }
        return false;
    }

    /**
     * 限购数量检测
     * @param $activity_goods_id
     * @param $num
     * @param $mid
     * @return array
     */
    public static function checkGoodsLimits(int $activity_goods_id, int $num, int $mid)
    {
        $todayOrdersNum = OrderGoodsModel::query()->where(['mid' => $mid, 'activity_goods_id' => $activity_goods_id,'status' => 0])->whereDate('create_at', date('Y-m-d'))->sum('number');
        $stock = ActivityGoodsModel::query()->where(['id' => $activity_goods_id])->value('stock');
        if ($todayOrdersNum) {
            if ($num > ($stock - $todayOrdersNum)) {
                return ['code' => ErrorCode::GOODS_NUM_OVER];
            }
        } else {
            if ($num > $stock) {
                return ['code' => ErrorCode::GOODS_NUM_OVER];
            }
        }
        return ['code' => ErrorCode::SUCCESS];

    }

    /**
     * 生成订单界面获取购物车列表
     * @param array $cartIds
     * @param int $mid
     * @return array
     */
    public function checkCart(int $mid,int $shop_id,int $source)
    {
        $field = [
            'id as cart_id',
            'goods_id',
            'goods_num',
            'is_selected',
            'status',
            'group_id',
            'activity_goods_id',

        ];

        $cartList = CartModel::where(['mid' => $mid, 'is_selected' => 1, 'status' => 0,'shop_id'=>$shop_id,'source'=>$source])->select($field)->get()->toArray();
        if (empty($cartList)) {
            return ['code' => ErrorCode::CART_NULL];
        }
        return ['code' => ErrorCode::SUCCESS, 'cartList' => $cartList];
    }
    /**
     * 校验库存购买数量大小及记录库存日志
     * @param int $stock
     * @param int $num
     * @param int $shop_id
     * @param int $goods_id
     * @param int $scant_id
     * @param int $radio
     * @return bool
     */
    public function checkStock(int $stock, int $num, int $shop_id,int $goods_id, int $scant_id, int $radio)
    {
        if ($stock < $num) {
            $info =
                [
                    'type' => 1,
                    'data' =>
                        [
                            'crmStock' => $stock,
                            'shop_id' => $shop_id,
                            'goods_num' => $num,
                            'goods_id' => $goods_id,
                            'scant_id' => $scant_id,
                            'ratio' => $radio,
                            'create_time' => date('Y-m-d H:i:s')
                        ]

                ];
//            (new LogQueueService())->handle($info);
            $this->cartLog->push(new LogJob($info),1);
            return false;
        } else {
            return true;
        }
    }

    /**
     * 记录日志
     * $type=0及时达 $type =1次日达
     * @param string $event
     * @param array $updateOrAddData
     * @param int $type
     * @param string $response
     * @return bool
     */
    public function saveCartLog(string $event, array $updateOrAddData, int $type, string $response)
    {
        $data = [
            'type' => 3,
            'data' => [
                'event' => $event,
                'params' => json_encode($updateOrAddData),
                'type' => $type,
                'response' => $response,
                'created_at' => date('Y-m-d H:i:s')
            ]
        ];
        $this->cartLog->push(new LogJob($data),1);
    }

    /**
     * 购物车列表
     * @param array $where
     * @param array|string[] $field
     * @return \Hyperf\Database\Model\Builder[]|\Hyperf\Database\Model\Collection
     */
    public static function cartList(array $where, array $field = ['*'])
    {
        $list = CartModel::query()->select($field)->where($where)->get()->toArray();
        return $list;
    }

    /**
     * 修改用户购物车商品全选全不选
     * @param $mid
     * @param $shop_id
     * @param $goodsId
     * @param $updateOrAddData
     * @return mixed
     */
    public static function setInfoByCartCheck(int $mid, int $shop_id, array $goodsId, array $updateOrAddData)
    {
        return CartModel::query()->where(['mid' => $mid,'shop_id'=>$shop_id])->whereIn('goods_id', $goodsId)->update($updateOrAddData); //更新商品
    }

    /**
     * 清空购物车
     * @param array $where
     * @return int|mixed
     */
    public static function deleteCart(array $where)
    {
        return CartModel::query()->where($where)->delete();
    }
    /**
     * 根据条件删除购物车
     * @param array $cartIds
     * @param int $mid
     */
    public function deleteCartById(array $cartIds,int $mid)
    {
        CartModel::whereIn('id',$cartIds)->where(['mid'=>$mid])->delete();
    }

    /**
     * 根据用户id获取购物车列表
     * @param array $cartList
     * @param array $tomorrowCartList
     * @param array $goodsId
     * @param array $tomorrowGoodsId
     * @param int $shop_id
     * @param int $mid
     * @return array
     */
    public static function getCartListArr(array $cartList, array $tomorrowCartList, array $goodsId, array $tomorrowGoodsId, int $shop_id,int $mid)
    {
        $cartEffectiveArr = self::getCartGoodsAll($cartList, $goodsId, $shop_id, $mid,self::GOODS_STATUS_0);
        $tomorrowEffectiveArr = CrdCartService::getCartGoodsAll($tomorrowCartList, $tomorrowGoodsId, $shop_id,$mid, CrdCartService::GOODS_STATUS_0);
        $cartFailArr = self::getCartGoodsAll($cartList, $goodsId, $shop_id, $mid,self::GOODS_STATUS_1);
        $tomorrowCartFailArr = CrdCartService::getCartGoodsAll($tomorrowCartList, $tomorrowGoodsId, $shop_id,$mid, CrdCartService::GOODS_STATUS_1);
        $res = [
            'cart_goods_list' => [
                'effective' => array_values($cartEffectiveArr['cartList']),
                'crdEffective' =>array_values($tomorrowEffectiveArr['cartList']),
                'fail' => array_merge($cartFailArr['cartList'], $tomorrowCartFailArr['cartList']),
            ]
        ];
        return $res;
    }

    /**
     * 获取商品 (status =0 is_deleted=1 库存<0  店铺下架)
     * $type=0有效 $type =1  无效
     * @param array $cartList
     * @param array $goodsId
     * @param int $shop_id
     * @param int $mid
     * @param int $type
     * @return array
     */
    public static function getCartGoodsAll(array $cartList, array $goodsId, int $shop_id, int $mid,int $type = 0)
    {
        //普通商品
        $goods = CartModel::query()->where('group_id','<>',3)->where(['mid'=>$mid,'shop_id'=>$shop_id,'source' =>1])->whereIn('goods_id',$goodsId)->select('goods_id')->get()->toArray();
        $goodsIds = array_column($goods,'goods_id');
        //限购商品
        $activityId = CartModel::query()->where(['group_id'=>3,'mid'=>$mid,'shop_id'=>$shop_id,'source' =>1])->select('goods_id','activity_goods_id')->get()->toArray();
        $activityIds = array_column($activityId,'activity_goods_id');
        $activityGoodsId = array_column($activityId,'goods_id');
        if ($type == self::GOODS_STATUS_0) {
            $goodsIdArr = GoodsModel::query()
                ->whereIn('id', $goodsIds)
                ->where(['is_deleted' => 0, 'status' => 1, 'is_today' => '1'])
                ->whereRaw('!FIND_IN_SET(?,shop_ids)', [$shop_id])
                ->pluck('id')
                ->toArray();
        } else {
            $goodsIdArr = GoodsModel::query()
                ->whereRaw("(FIND_IN_SET({$shop_id},shop_ids) OR is_deleted = 1 OR status = 0 OR is_today = '0')")
                ->whereIn('id',$goodsIds)
                ->pluck('id')
                ->toArray();
        }
        //当前店铺有效活动商品
        $activityGoodsIdRes = ActivityModel::query()->from('store_activity_goods as g')
            ->join('store_activity as s','s.activityID','=', 'g.activityID')
            ->join('store_goods as t','t.id','=','g.goods_id')
            ->where(['g.is_deleted' => 0, 's.is_deleted' => 0,'g.group_id' => 3])
            ->where('g.stock','>',0)
            ->where('s.status','<>',0)
            ->where('s.end_date','>=',date('Y-m-d H:i:s'))
            ->where(['t.is_deleted' => 0, 't.status' => 1 ,'t.is_today' => '1'])
            ->whereIn('g.id',$activityIds)
            ->whereIn('t.id',$activityGoodsId)
            ->whereRaw('!FIND_IN_SET(?,t.shop_ids)', [$shop_id])
            ->whereRaw('FIND_IN_SET(?,s.shop_ids)', [$shop_id])
            ->pluck('g.id')
            ->toArray();
        //当前用户已购买活动商品数
        $order_Num =OrderGoodsModel::query()->from('store_order_goods as g')->join('store_order as o', 'o.order_no', '=', 'g.order_no')
            ->whereIn('o.status', [1, 2, 3, 4, 6, 7, 8])
            ->where(['o.mid' => $mid,'o.order_source'=>0])
            ->whereIn('g.activity_goods_id',$activityGoodsIdRes)
            ->groupBy(['g.activity_goods_id'])
            ->selectRaw('sum(g.number - g.refund_number - g.shop_refund_number) as num,activity_goods_id')
            ->get()->toArray();
        $orderNUM = array_column($order_Num,null,'activity_goods_id');
        //当前活动的每人限购数
        $actNum = ActivityGoodsModel::query()->where('group_id','=',3)->whereIn('id',$activityGoodsIdRes)->select('id','stock')->get()->toArray();
        $NUM = array_column($actNum,null,'id');
        //当前用户还能够买数量
        $midNumber = [];
        foreach ($actNum as $k => $v){
            if(isset($orderNUM[$actNum[$k]['id']])){
                $midNumber[$k]['number'] = $NUM[$actNum[$k]['id']]['stock'] - $orderNUM[$actNum[$k]['id']]['num'];
                $midNumber[$k]['activity_goods_id'] = $NUM[$actNum[$k]['id']]['id'];
            }else{
                $midNumber[$k]['number'] = $NUM[$actNum[$k]['id']]['stock'];
                $midNumber[$k]['activity_goods_id'] = $NUM[$actNum[$k]['id']]['id'];
            }
        }
        $midNumber = array_column($midNumber,'number','activity_goods_id');
        $validcart = CartModel::query()->where(['group_id'=>3,'mid'=>$mid,'shop_id'=>$shop_id,'source'=>1])->whereIn('activity_goods_id',$activityGoodsIdRes)->select('goods_num','activity_goods_id')->get()->toArray();
        $validcart = array_column($validcart,'goods_num','activity_goods_id');
        //当前用户有效的活动商品id
        $activity_goods_id = [];
        foreach ($midNumber as $k => $v){
            if($midNumber[$k] >= $validcart[$k] ){
                $activity_goods_id[] = $k;
            }
        }
        if($type == self::GOODS_STATUS_0){
            $activityGoodsIdArr = $activity_goods_id;
        }else{
            $activityGoodsIdArr = CartModel::query()->where(['group_id'=>3,'mid'=>$mid,'shop_id'=>$shop_id,'source' =>1])->whereNotIn('activity_goods_id',$activity_goods_id)->pluck('activity_goods_id')->toArray();
        }
        $goodsField = ['goods_id','goods_title','goods_logo','goods_spec','costprice','price_selling','per_can_buy_num','group_id','id'];
        $_activityGoodsIdArr = ActivityGoodsModel::query()->where('group_id','=',3)->whereIn('id',$activityGoodsIdArr)->select($goodsField)->get()->toArray();
        $activityId = array_column($_activityGoodsIdArr,'goods_id');
        $actListArr = array_column($_activityGoodsIdArr,null,'goods_id');
        $activityCart = CartModel::query()->whereIn('goods_id',$activityId)->where(['group_id'=>3,'mid'=>$mid,'shop_id'=>$shop_id,'source' =>1])->select('id','goods_id')->get()->toArray();
        $activitygoodsId = array_column($activityCart,'id','id');
        $goodsCart = CartModel::query()->whereIn('goods_id',$goodsIdArr)->where('group_id','<>',3)->where(['mid'=>$mid,'shop_id'=>$shop_id,'source' =>1])->select('id','goods_id')->get()->toArray();
        $GoodsId = array_column($goodsCart,'id','id');
        $_goodsListArr = GoodsService::getGoodsInfoData($shop_id, $goodsIdArr, GoodsService::STOCK_TYPE_1);
        $goodsListArr = array_column($_goodsListArr, null, 'goods_id');
        $goodsArr = array_merge($activitygoodsId,$GoodsId);
        $goodsIdRes = array_flip($goodsArr);
        foreach ($cartList as $k => &$v) {
            if (!isset($goodsIdRes[$v['id']])) {
                unset($cartList[$k]);
                continue;
            }
            if (isset($activitygoodsId[$v['id']])) {
                $v['title'] = $actListArr[$v['goods_id']]['goods_title'];
                $v['logo'] = $actListArr[$v['goods_id']]['goods_logo'];
                $v['goods_spec'] = $actListArr[$v['goods_id']]['goods_spec'];
                $v['activity_goods_id'] = $actListArr[$v['goods_id']]['id'];
                $v['price_selling'] = bcmul($actListArr[$v['goods_id']]['price_selling'], '100');
                $v['price_market'] = bcmul($actListArr[$v['goods_id']]['costprice'], '100');
            } else {
                $v['title'] = $goodsListArr[$v['goods_id']]['title'];
                $v['logo'] = $goodsListArr[$v['goods_id']]['logo'];
                $v['goods_spec'] = $goodsListArr[$v['goods_id']]['goods_spec'];
                $v['activity_goods_id'] = 0;
                $v['price_selling'] = bcmul($goodsListArr[$v['goods_id']]['price_selling'], '100');
                $v['price_market'] = bcmul($goodsListArr[$v['goods_id']]['price_market'], '100');
            }
        }
        return compact("cartList");
    }

    /**
     * 删除无效商品
     * @param int $shop_id
     * @param int $mid
     * @return int|mixed
     */
    public static function deleteNoCart(int $shop_id, int $mid)
    {
        $field = [
            'id',
            'mid',
            'goods_id',
            'goods_num',
            'is_selected',
            'activity_goods_id',
            'group_id',
            'source'
        ];
        $cartList = self::cartList(['mid' => $mid,'shop_id'=>$shop_id,'source'=>1], $field);
        $goodsId = array_column($cartList, 'goods_id');
        $arr = self::getCartGoodsAll($cartList, $goodsId, $shop_id, $mid,self::GOODS_STATUS_1);
        $goodsRes = array_column($arr['cartList'],'goods_id');
        if (!$goodsRes) {
            return true;
        }
        $res = CartModel::query()->where(['mid' => $mid,'shop_id'=>$shop_id,'source'=>1])->whereIn('goods_id', $goodsRes)->delete();
        return $res;
    }

    /**
     * 获取购物车商品选中数量
     *
     * @param int $mid
     * @param int $shop_id
     * @return int
     */
    public function cartGoodsNumber(int $mid ,int $shop_id)
    {

        $cartNum = intval(CartModel::query()->where(['mid'=>$mid,'shop_id'=>$shop_id,'is_selected'=>1])->sum('goods_num') ?: 0);
        return $cartNum;
    }

    /**
     * 添加购物车
     * @param array $updateOrAddData
     * @return
     */
    public function cartInsert(array $updateOrAddData){
       return CartModel::query()->insert($updateOrAddData);
    }
}
